//
//  connection.cpp
//  api-server
//
//  Created by Peter Emil Jensen on 26/08/2012.
//  Copyright (c) 2012 Peter Emil Jensen. All rights reserved.
//

#include "connection.h"
#include <vector>
#include <boost/bind.hpp>
#include <stdio.h>

connection::connection(boost::asio::io_service& io_service) : strand_(io_service), socket_(io_service)
{
    std::stringstream ss;
    size_t size = 0;
    
    json_ptr.reset(new json());
    std::string tmp_dump = json_ptr->dump();
    std::string tmp_header = "HTTP/1.1 200 OK\r\nServer: custom\r\nContent-Length: ";
    
    size = tmp_dump.size();
    ss << size;
    
    tmp_header += ss.str();
    tmp_header += "\r\nContent-Type: text/plain; charset=UTF-8\r\nConnection: close\r\n\r\n";
    
    json_dump = tmp_header;
    json_dump += tmp_dump;
    json_dump += "\r\n";
}

boost::asio::ip::tcp::socket& connection::socket()
{
    return socket_;
}

void connection::start()
{
    socket_.async_read_some(boost::asio::buffer(buffer_), strand_.wrap(boost::bind(&connection::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)));
}

void connection::handle_read(const boost::system::error_code& e, std::size_t bytes_transferred)
{
    if (!e)
    {
        boost::asio::async_write(socket_, boost::asio::buffer(json_dump), strand_.wrap(boost::bind(&connection::handle_write, shared_from_this(), boost::asio::placeholders::error)));
    }
}

void connection::handle_write(const::boost::system::error_code& e)
{
    if (!e)
    {
        boost::system::error_code ignored_ec;
        socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
    }
}